<?php 
namespace app\mall\controller;
//use app\mall\controller\Base;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\Request;
use app\mall\model\Goods as GoodsModel;
use app\mall\service\GoodsService;
use app\mall\model\GoodsSpec;
use app\mall\model\GoodsSpecDetail;
//use app\comm\service\GoodsService as GoodsServ;
//use app\mall\model\GoodsCategory;

class Goods extends BasicAdmin{
    public $table = 'GoodsSpecName';
    /*********************************商品分区**************************************************************************/
    /**
     * 商品列表
     * @return [type] [description]
     */
    public function goods(){
        $this->title = '商品列表';
        $get = request()->get();
        $map = array();
        $map['a.is_deleted'] = array('eq',0);
        $map['a.store_id'] = array('eq',0);
        if(!empty($get['name'])){
            $map['a.name'] = array('like',"%".$get['name']."%");
        }
        $rows = intval(request()->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $page = Db::name('goods')->alias('a')->join('ys_goods_category b','a.cat_id=b.id','LEFT')->join('ys_goods_label c','a.goods_sign=c.id','LEFT')->where($map)->field('a.*,b.title,(select count(*) from ys_goods_spec_detail as c where a.id=c.goods_id and c.specs=0 and c.is_deleted=0) as n_spec,c.sign')->order('id desc')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())];

        $where = [
            'a.is_deleted'=>0,
            'b.is_deleted'=>0,
            'a.stock'=>['lt','a.warn_stock']
        ];

        $sql = "select count(*) as count from ys_goods_spec_detail as a left join ys_goods as b on a.goods_id=b.id where a.is_deleted=0 and b.is_deleted=0 and a.stock<a.warn_stock";
        $stock_caveat  = Db::query($sql);//查看缺货商品数量
        $yangshi = config("qiniu");

        $this->assign('yangshi',$yangshi['yangshi']);          //七牛样式后缀
        $this->assign('title',$this->title);
        $this->assign('stock_caveat',$stock_caveat);            //缺货商品数量

        return $this->fetch('goods',$result);
    }
    /**
     * 添加 -- 编辑商品
     */
    public function add_goods(){
        if(request()->isPost()){
            $GoodsModel = new GoodsModel();      //商品模型
            $post = input('post.');
//            if(!empty($post['goods_label'])){
//                $post['goods_label'] = implode(',',$post['goods_label']);
//            }else{
//                $post['goods_label'] = '';
//            }
            $post['addtime'] = time();
            $post['logo'] = trim($post['logo']);        //去掉两端空格
            $images = array_unique(explode('|',trim($post['images'])));
            $post['images']= implode('|',array_filter($images));
            $result = $GoodsModel->add_edit($post);
//            if(($result['code'] == 1) && !empty($post['spec_id'])){
//                $model = new GoodsSpec();
//                $spec = $this->spec_group($post,$result['goods_id']);
//                $res = $model->saveall($spec);
//                $res>0?$result['code'] = 1:$result['code'] = 0;
//                Db::name('goods')->where('id',$result['goods_id'])->update(['is_spec'=>1]);     //更新商品有属性状态
//            }
            $result['code'] == 1?$this->success('保存成功',url('@admin').'#'.url('Goods/goods').'?spm='.input('spm')):$this->error($result['msg'],'');
        }
        $id = input('id');
        $vo = Db::name('goods')->where('id',$id)->find();
        if(!empty($vo)){
            $vo['goods_label'] = explode(',',$vo['goods_label']);
        }else{
            $vo['goods_label'] = array();
        }

        $goods_label = db('goods_label')->where('is_deleted',0)->select();          //商品标签
        $category = Db::name('goods_category')->where(['status'=>1,'is_exp'=>0,'is_deleted'=>0])->select();         //商品分类
        $exp_category = Db::name('goods_category')->where(['status'=>1,'is_exp'=>1,'is_deleted'=>0])->select();     //商品扩展分类
        $spec = Db::name('goods_spec_name')->where('is_deleted',0)->select();
        $shuxing = Db::name('goods_spec')->where('goods_id',$id)->select();     //属性
        $level = db('sys_level')->order('score asc')->select();


        if(!empty($vo['images'])){
            $this->assign('images',explode('|',$vo['images']));
        }else{
            $this->assign('images',array());
        }
        $this->assign('shuxing',$shuxing);
        $this->assign('goods_label',$goods_label);
        $this->assign('category',$category);
        $this->assign('exp_category',$exp_category);
        $this->assign('spec',$spec);            //商品属性名称
        $this->assign('level',$level);            //商品属性名称
        $this->assign('vo',$vo);
        $this->assign('title','编辑商品');


        if(empty($id)){
            return $this->fetch('add_goods');
        }else{
            return $this->fetch('edit_goods');
        }
    }
    /**
     * 商品 -- 上架
     */
    public function on_sall()
    {
        $post = input('post.');
        $res = Db::name('goods')->where('id', $post['id'])->update(['status' => $post['value']]);
        $res !== false ? $this->success('上架成功', '') : $this->error('上架失败', '');
    }
    /**
     * 商品 -- 下架
     * @return [type] [description]
     */
    public function down_sall(){
        $post = input('post.');
        $res = Db::name('goods')->where('id',$post['id'])->update(['status'=>$post['value']]);
        $res!==false?$this->success('下架成功',''):$this->error('下架失败，请稍后再试！','');
    }
    /**
     * 删除
     * @return [type] [description]
     */
    public function del_goods(){
        $table = "Goods";
        if (DataService::update($table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    /**
     * @Author  lingyun
     * @Desc    推荐商品
     * 2018-03-24
     */
    public function set_top(){
        $id = input('id');
        $model = new GoodsModel();
        $flag = $model->set_top($id);
        $flag['code']!=0?$this->success('设置成功',''):$this->error($flag['msg'],'');
    }

    /**
     * @Author  lingyun
     * @Desc    商品库存报警
     * 2018-03-24
     */
    public function goods_stock_caveat(){
        $this->title = '缺货商品';
        $db = Db::name('goods_spec_detail')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where(['a.is_deleted'=>0,'b.is_deleted'=>0])->where('a.stock','gt','a.warn_stock')->field('a.goods_id,a.title,a.stock,b.price,b.name,a.id');
//        halt($db);
//        $db = "select a.goods_id,a.title,a.stock,b.price,b.name,a.id from ys_goods_spec_detail as a left join ys_goods as b on a.goods_id=b.id where a.is_deleted=0 and b.is_deleted=0 and a.stock<a.warn_stock";

        return parent::_list($db);
    }

    /*********************************商品分区**************************************************************************/
    /*********************************商品属性**************************************************************************/
    /**
     * 删除商品属性
     * @return [type] [description]
     */
    public function del_spec(){
        $id = input('id');
        $res = Db::name('goods_spec')->delete(['id'=>$id]);
        $res>0?$this->success('删除成功',''):$this->error('删除失败','');
    }
    /**
     * 编辑商品属性
     * @return [type] [ ]
     */
    public function goods_spec_name(){
        $this->title = '商品属性';
        $get = $this->request->get();
        $db = Db::name('goods_spec_name')->where(['is_deleted' => '0']);
        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db);
    }
    /**
     * 编辑商品属性
     */
    public function add_goods_spec_name(){
        $this->assign('time',time());       //添加的时间
        return $this->_form('GoodsSpecName', 'add_goods_spec_name','id');        //保存数据
    }
    /**
     * 删除商品属性名称
     * @return [type] [description]
     */
    public function del_goods_spec_name(){
        $table = "GoodsSpecName";
        if (DataService::update($table)) {
            $this->success("用户删除成功！", '');
        }
        $this->error("用户删除失败，请稍候再试！");
    }

    /**
     * 添加商品属性
     * dikaer()字符串   dikaerr数组
     */
    public function add_goods_spec(){
        if(request()->isPost()){
            $post = input('post.');     //接受的数据
            $da = $this->spec_group($post,$post['id']);
            $goodsspecmodel = new GoodsSpec();
            if(!empty($da)){
                $res = $goodsspecmodel->saveall($da);
                if($res>0){
                    $this->redirect('create_goods_spec',array('id'=>$post['id']));      //跳转生成商品属性
                    // $this->success('成功','');
                    // $result['code'] = 1;
                }else{
                    $this->error('规格生成失败','');
                    // $result['code'] = 0;
                }
            }
        }else{
            $id = input('id');      //商品id
            $spec_cate = Db::name('goods_spec_name')->field('id,name')->select();        //属性分类名称
            $this->assign('spec_cate',$spec_cate);
            $this->assign('id',$id);
            $this->assign('title','添加商品属性');
            return $this->fetch('add_goods_spec');
        }
    }
    /**
     * 生成商品属性
     * 组合生成一个隐藏域，进行属性的编辑
     * @return [type] [description]
     */
    public function create_goods_spec(){
        if(request()->isPost()){
            $post = input('post.');
            $model = new GoodsSpecDetail();
            $specs = $this->spec_arr($post,$post['goods_id']);
            $res = $model->saveall($specs);
            $res>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $goods_id = input('id');
            // $count = Db::name('goods_spec_detail')->where(['goods_id'=>$goods_id,'is_deleted'=>0])->select();       //查看配方的属性
            $spec = Db::name('goods_spec')->alias('a')->join('ys_goods_spec_name b','a.spec_id=b.id','LEFT')->where('a.goods_id',$goods_id)->field('a.id,a.detail,a.spec_id,b.name')->select();      //属性的详情
            foreach($spec as $k => $v){
                $spec_arr[$v['spec_id']][] = $v['id'];                  //属性id数组
                $spec_name[$v['spec_id']][] = $v['name'].": ".$v['detail'];             //属性名称数组
            }
            $spec_names = dikaerr($spec_name);      //组合属性名称数组
            $spec_res = array();
            foreach($spec_names as $kk => $vv){
                if(count($spec_names[$kk]) > 1){
                    $spec_res[$kk][0] = implode(" ",$spec_names[$kk]);
                }else{
                    $spec_res[$kk][0] = $spec_names[$kk];
                }

            }
            $spec_arrs  = dikaer($spec_arr);         //组合属性id字符串
            foreach($spec_res as $k1 => $v1){
                $spec_res[$k1]['specs'] = $spec_arrs[$k1];
                $spec_res[$k1]['price'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('price');
                $spec_res[$k1]['id'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('id');
                $spec_res[$k1]['recipe_ratio'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('recipe_ratio');
                $spec_res[$k1]['score'] = Db::name('goods_spec_detail')->where('specs',$spec_arrs[$k1])->value('score');
            }
            $this->assign('goods_id',$goods_id);
            $this->assign('spec_res',$spec_res);            //模板渲染数据
            $this->assign('title','商品属性');
            return $this->fetch('create_goods_spec');
        }
    }
    /**
     * 单个商品属性的组合
     * @return [type] [description]
     */
    public function group_goods_spec(){
        if(request()->isPost()){
            $post = input('post.');
            $goodspecmodel = new GoodsSpec();
            $model = new GoodsSpecDetail();
            $specs = $this->signal_goods_arr($post,$post['goods_id']);
            // halt($specs);
            $res = $goodspecmodel->saveall($specs[0]);
            $res = $model->saveall($specs[1]);
            $res>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $goods_id = input('id');
            $spec_id = Db::name('goods')->where('id',$goods_id)->value('goods_spec');           //商品的限制住的属性分类请先
            if(!$spec_id){
                $this->error('该商品没有添加规格，请先添加规格','');
            }
            $spec_name = Db::name('goods_spec_name')->where('id',$spec_id)->field('id,name,addtime')->find();      //属性分类名称
            $spec = Db::name('goods_detail')->alias('a')->join('ys_goods_spec_name b','a.specs=b.id','LEFT')->where('goods_id',$goods_id)->field('a.')->select();
            $this->assign('goods_id',$goods_id);
            $this->assign('spec_name',$spec_name);            //模板渲染数据
            $this->assign('title','商品属性');
            return $this->fetch('group_goods_spec');
        }
    }
    /**
     * 商品单属性分类
     * @return [type] [description]
     */
    private function signal_goods_arr($data,$goods_id){
        $price = $data['price'];
        $detail = $data['detail'];
        $recipe_ratio = $data['recipe_ratio'];
        foreach($price as $k => $v){
            $arr1[$k]['spec_id'] = $data['spec_id'];     //goods_spec表
            $arr1[$k]['goods_id'] = $goods_id;
            $arr1[$k]['detail'] = $detail[$k];
            $arr1[$k]['addtime'] = time();
            $arr2[$k]['goods_id'] = $goods_id;              //goods_spec_detail表
            $arr2[$k]['price'] = $v;
            $arr2[$k]['specs'] = $data['spec_id'];
            $arr2[$k]['addtime'] = time();
            $arr2[$k]['recipe_ratio'] = $recipe_ratio[$k];
        }
        $da[0] = $arr1;
        $da[1] = $arr2;
        return $da;
    }
    /**
     * 添加属性是进行输出
     * @return [type] [description]
     */
    private function spec_group($data,$goods_id){
        $spec_id = $data['spec_id'];            //商品属性ID
        $spec = $data['details'];          //商品属性名称
        foreach($spec_id as $k => $v){
            if(!empty($s_id)){
                $res[$k]['id'] = $data['sid'][$k];
            }
            $res[$k]['spec_id'] = $v;
            $res[$k]['goods_id'] = $goods_id;
            $res[$k]['detail'] = $spec[$k];
            $res[$k]['addtime'] = time();
        }
        return $res;
    }
    /**
     * 构造商品属性数组数据
     * @param  [type] $data     接受的数据
     * @param  [type] $goods_id 商品ID
     * @return [type]           返回入库的数据
     */
    private function spec_arr($data,$goods_id){
        $specs = $data['specs'];       //属性id
        if(isset($data['price'])){
            $price = $data['price'];        //价格
        }
        if(isset($data['id'])){
            $id = $data['id'];
        }
        $title = $data['title'];        //属性的标题
        $score = $data['score'];        //商品积分
        foreach($specs as $k => $v){
            $spec[$k]['specs'] = $v;
            $spec[$k]['title'] = $title[$k];
            $spec[$k]['goods_id'] = $goods_id;
            if(isset($price[$k])){
                $spec[$k]['price'] = $price[$k];
            }
            if(isset($score[$k])){
                $spec[$k]['score'] = $score[$k];
            }
            if(isset($id[$k])){
                $spec[$k]['id'] = $id[$k];
            }
            $spec[$k]['addtime'] = time();
        }
        return $spec;           //返回入库数据
    }

    /**
     * @Author  lingyun
     * @Desc    商品标签
     * 2018-03-19
     */
    public function set_goods_label(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            //设置标签的商品
            $goods = db('goods')->where('id',$post['id'])->find();
            if(!empty($post['goods_label'])){
                $post['goods_label'] = implode(',',$post['goods_label']);
            }else{
                $post['goods_label'] = '';
            }

            $res = db('goods')->where('id',$post['id'])->update(['goods_label'=>$post['goods_label']]);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }
        $id = input('id');
        $where_goods_label = [
            'status'=>1,
            'is_deleted'=>0
        ];
        $goods = db('goods')->where('id',$id)->value('goods_label');
        if(!empty($goods)){
            $goods = explode(',',$goods);
        }else{
            $goods = array();
        }
        $this->assign('goods',$goods);
        $goods_label = db('goods_label')->where($where_goods_label)->select();
        $this->assign('goods_label',$goods_label);
        $this->assign('id',$id);
        return $this->fetch('set_goods_label');
    }

    /**
     * @Author  lingyun
     * @Desc    设置商品标志
     * 2018-03-19
     */
    public function set_goods_sign(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $goods = db('goods')->where('id',$post['id'])->find();
            $res = db('goods')->where('id',$post['id'])->update(['goods_sign'=>$post['goods_sign']]);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $id = input('id');
            $goods = db('goods')->where('id',$id)->field('id,name,goods_sign')->find();

            //商品标签
            $sign = db('goods_label')->where(['status'=>1,'is_deleted'=>0])->select();
            $this->assign('id',$id);
            $this->assign('sign',$sign);
            $this->assign('goods',$goods);

            return $this->fetch('set_goods_sign');
        }
    }
    /*********************************商品属性**************************************************************************/

    /*********************************商品评论**************************************************************************/
    /**

     * 商品评论操作

     * @yunhaiyidao

     */

    public function comment(){
        $this->title = '商品评论';

        $get = $this->request->get();
        $join = [
            ['ys_goods b','a.goods_id=b.id','LEFT'],
            ['ys_user c','a.uid=c.uid','LEFT'],
        ];

        $db = db('goods_comment')->alias('a')->join($join)->field('a.*,b.name,c.realname,c.nickname')->where('a.is_deleted',0);


        // foreach (['title'] as $key) {

        //     (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");

        // }

        return parent::_list($db);
    }

    /**

     * 商品品论操作

     * @yunhaiyidao

     */

    public function comment_shows(){

        $id = input('id');

        $info = db('goods_comment')->where('id',$id)->find();
        $is_show = abs($info['is_show']-1);
        $res = db('goods_comment')->where('id',$id)->update(['is_show'=>$is_show]);
        $res!==false?$this->success('设置成功',''):$this->error('设置失败','');

    }

    /**

     * 商品品论详情

     * @yunhaiyidao

     */

    public function comment_detail(){
        $id = input('id');
        $info = db('goods_comment')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_user c','a.uid=c.uid','LEFT')->where('a.id',$id)->field('a.*,b.name,c.realname,c.nickname')->find();
        if(!empty($info['images'])){
            $info['images'] = explode(',', $info['images']);
        }else{
            $info['images']  = array();
        }
        $this->assign('info',$info);

        return $this->fetch();

    }
    /*********************************商品评论**************************************************************************/

    /*********************************商品评论**************************************************************************/

    /*********************************商品运费管理***********************************************************************/
    /**
     * @Author lignyun
     * @Desc    商品运费
     */
    public function goodDeliveryFee(){
        $this->title = '商品分类';
        $get = $this->request->get();
        $db = Db::name('delivery_fee')->where('is_deleted',0);
        foreach (['title'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db);
    }
    /**
     * @Author lignyun
     * @Desc    添加运费规则
     */
    public function add_delivery_fee(){
        if(request()->isPost()){
            $post = input('post.');
            if(empty($post['id'])){
                $post['addtime'] = time();      //添加时间
                $res = Db::name('delivery_fee')->insert($post);
                $res>0?$this->success('保存成功',''):$this->error('保存失败，请重试！');
            }else{
                $res = Db::name('delivery_fee')->update($post);
                $res!==false?$this->success('保存成功',''):$this->error('保存失败，请重试！');
            }
        }
        $id = input('id');
        //运费信息
        $info = Db::name('delivery_fee')->where('id',$id)->find();
        $this->assign('info',$info);
        return $this->fetch('add_delivery_fee');
    }
    /**
     * @Author lignyun
     * @Desc    删除运费
     */
    public function del_delivery_fee(){
        $table = 'DeliveryFee';
//        $post = input('post.');
//        $res = Db::name('delivery_fee')->where('id',$post['id'])->update(['is_deleted'=>1]);
//        $res!==false?$this->success('删除成功!',''):$this->error('删除失败!','');

        if (DataService::update($table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    /*********************************商品运费管理***********************************************************************/

    /*********************************商品标签区***********************************************************************/
    /**
     * @Author  lingyun
     * @Desc    商品标签
     */
    public function goods_label(){
        $this->title = '商品标签';
        $get = $this->request->get();
        $db = Db::name('goods_label')->where('is_deleted',0);
        foreach (['title'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑商品标签
     */
    public function add_edit_goods_label(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            if(empty($post['id'])){
                $post['addtime'] = time();
                $res = db('goods_label')->data($post)->insert();
                $res>0?$this->success('保存成功',''):$this->error('保存失败','');
            }else{
                $res = db('goods_label')->update($post);
                $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
            }
        }else{
            $id = input('id');
            $label = db('goods_label')->where('id',$id)->find();
            $this->assign('label',$label);
            return $this->fetch('add_edit_goods_label');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    设置商品标签状态
     */
    public function set_goods_label_status(){
        $post = input('post.');
        $res = db('goods_label')->update(['id'=>$post['id'],$post['field']=>$post['value']]);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    删除商品标签
     */
    public function del_goods_label(){
        $table = 'GoodsLabel';
        if (DataService::update($table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }
    /*********************************商品标签区***********************************************************************/
    /*********************************商品图集区**********************************************************************/
    /**
     * @Author  lingyun
     * @Desc    商品图集 -- 添加 -- 编辑
     */
    public function goods_images(){
        $service = new GoodsService();
        $request = request();
        if($request->isPost()){
            $post = input('post.');
//            halt($post);
            $res = db('goods')->update($post);
            $res !== false?$this->success('保存成功',url('@admin').'#'.url('Goods/goods').'?spm='.input('spm')):$this->error('保存失败',url('@admin').'#'.url('Goods/goods').'?spm='.input('spm'));
        }

        $id = input('id');
        $info = db('goods')->where('id',$id)->find();
        $images = explode('|',$info['images']);             //商品详情图片
        $pc_banner = explode('|',$info['pc_banner']);       //电脑版海报
        $mo_banner = explode('|',$info['mo_banner']);       //手机版海报

        $this->assign('info',$info);
        $this->assign('id',$id);
        $this->assign('title','商品图集');
        $this->assign('images',$images);
        $this->assign('pc_banner',$pc_banner);
        $this->assign('mo_banner',$mo_banner);

        return $this->fetch('goods_images');
    }

    /**
     * @Author  lingyun
     * @Desc    删除图集中的轮播图
     */
    public function del_pic(){
        $post = input('post.');
        $res = db('goods')->update($post);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    删除电脑版海报图片
     */
    public function del_pc_banner(){
        $post = input('post.');
        $res = db('goods')->update($post);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    删除手机版海报图片
     */
    public function del_mo_banner(){
        $post = input('post.');
        $res = db('goods')->update($post);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }



}
?>